import java.util.Stack;

public class MySingleLIst {
    class Node {
        public int val;//存储数据
        public Node next;//存储下一个节点的地址

        public Node(int val) {
            this.val = val;
        }
    }

    public Node head;

    //递归打印链表
    public void display(Node pHead) {
        if (pHead == null) {//pHead为空
            return;
        }
        if (pHead.next == null) {//pHead只有一个节点
            System.out.print(pHead.val + " ");
        }
        //上述两个if可以做为递归的结束条件
        display(pHead.next);//自己调用自己，递归
        System.out.println(pHead.val + " ");
    }

    public void display1() {
        //将链表当中的节点保存在栈中
        Stack<Node> stack = new Stack<>();//申请一个栈，这个栈中放的是一个一个的节点
        Node cur = head;
        while (cur != null) {//栈中有节点，进入循环
            stack.push(cur);//给第一个节点放入数字
            cur = cur.next;//向后走
        }
        //遍历栈
        while (!stack.isEmpty()) {
            Node top = stack.pop();
            System.out.print(top.val + " ");
        }
        System.out.println();
    }

    public void addLast(int data) {
        Node node = new Node(data);
        if (head == null) {
            head = node;
            return;
        }
        Node cur = head;
        while (cur.next != null) {
            cur = cur.next;
        }
        cur.next = node;
    }

    public void push(int val) {
        Node node = new Node(val);
        node.next = head;
        node = head;
    }

    public Object pop() {
        if (head == null) {
            return null;
        }
        Node headNext = head.next;
        head.next = null;
        head = headNext;
        headNext = headNext.next;
        return head.val;
    }
}

